package com.dempsey.modules.file.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.IdUtil;
import com.dempsey.common.core.exception.file.FileReadException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

/**
 * @author Dempsey
 * Date 2022/5/20
 * Description
 */

public class FileUtil {

    static final int HEAD_IMAGE_WIDTH = 180;
    static final int HEAD_IMAGE_HEIGHT = 180;


    /**
     * 将 multipartFile转换为File，会在项目根目录产生临时文件，记得删掉
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile;
        try {
            InputStream ins = file.getInputStream();
            toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            ins.close();
        } catch (Exception e) {
            throw new FileNotFoundException();
        }
        return toFile;

    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            throw new FileReadException();
        }
    }

    /**
     * 重命名文件名
     *
     * @param fileName 文件名
     * @return the string
     */
    public static String extractFilename(String fileName) {
        String extension = getExtension(fileName);
        String filename = IdUtil.simpleUUID();
        fileName = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN) + "-" + filename + "." + extension;
        return fileName;
    }

    /**
     * 获取文件名的后缀
     *
     * @param fileName 文件名
     * @return 后缀名
     */
    public static String getExtension(String fileName) {
        return FilenameUtils.getExtension(fileName);
    }


    /**
     * 缩放图片 img file.
     *
     * @param srcImageFile  the src image file
     * @param destImageFile the dest image file
     * @return the file
     */
    public static void scaleHeadImg(File srcImageFile, File destImageFile) {
        ImgUtil.scale(srcImageFile, destImageFile, HEAD_IMAGE_WIDTH, HEAD_IMAGE_HEIGHT, null);
    }

}
